import React, { useState, useEffect } from 'react';
import {
  Container, Typography, Grid, Card, CardContent, CardActions,
  Button, Box, LinearProgress, Dialog, DialogTitle, DialogContent,
  DialogActions, IconButton, Avatar, Chip, Tooltip, Alert, CircularProgress
} from '@mui/material';
import {
  EmojiEvents as TrophyIcon,
  Timer as TimerIcon,
  Stars as StarsIcon,
  Close as CloseIcon
} from '@mui/icons-material';
import axios from 'axios';
import { useAuth } from '../contexts/AuthContext';
import { useNavigate } from 'react-router-dom';
import LoginDialog from '../components/LoginDialog';

const challenges = [
  {
    id: 1,
    title: "零塑料周",
    description: "一周内不使用任何一次性塑料制品",
    points: 100,
    duration: "7天",
    category: "生活方式",
    difficulty: "中等",
    progress: 0,
    icon: "🌱",
    tasks: [
      { text: "自带购物袋", points: 20 },
      { text: "使用可重复使用的水杯", points: 20 },
      { text: "拒绝一次性餐具", points: 30 },
      { text: "选择无包装商品", points: 30 }
    ],
    tips: "准备一个环保购物套装，包含购物袋、水杯和餐具"
  },
  {
    id: 2,
    title: "绿色出行",
    description: "连续5天使用公共交通或步行上下班",
    points: 80,
    duration: "5天",
    category: "交通",
    difficulty: "简单",
    progress: 0,
    icon: "🚲",
    tasks: [
      { text: "规划公交路线", points: 15 },
      { text: "准备自行车装备", points: 15 },
      { text: "记录每日出行方式", points: 25 },
      { text: "分享绿色出行体验", points: 25 }
    ],
    tips: "提前查看天气，合理安排出行时间"
  },
  {
    id: 3,
    title: "节能达人",
    description: "将本月用电量较上月减少10%",
    points: 150,
    duration: "30天",
    category: "能源",
    difficulty: "困难",
    progress: 0,
    icon: "⚡",
    tasks: [
      { text: "记录用电数据", points: 30 },
      { text: "使用节能电器", points: 40 },
      { text: "养成随手关灯习惯", points: 40 },
      { text: "控制空调温度", points: 40 }
    ],
    tips: "使用智能插座监控用电量"
  },
  {
    id: 4,
    title: "垃圾分类达人",
    description: "连续14天正确进行垃圾分类",
    points: 120,
    duration: "14天",
    category: "废物处理",
    difficulty: "中等",
    progress: 0,
    icon: "♻️",
    tasks: [
      { text: "学习垃圾分类知识", points: 20 },
      { text: "准备分类垃圾桶", points: 30 },
      { text: "正确进行日常分类", points: 40 },
      { text: "指导他人进行分类", points: 30 }
    ],
    tips: "下载垃圾分类指南APP，遇到不确定的物品可以查询"
  },
  {
    id: 5,
    title: "食物零浪费",
    description: "一周内不浪费任何食物",
    points: 90,
    duration: "7天",
    category: "饮食",
    difficulty: "中等",
    progress: 0,
    icon: "🥗",
    tasks: [
      { text: "合理规划采购量", points: 20 },
      { text: "学习食材保存方法", points: 20 },
      { text: "制作剩余食材餐", points: 25 },
      { text: "记录每日食物消耗", points: 25 }
    ],
    tips: "建议制定每周菜单，根据菜单采购食材"
  },
  {
    id: 6,
    title: "植物守护者",
    description: "种植和照顾一株植物30天",
    points: 100,
    duration: "30天",
    category: "园艺",
    difficulty: "简单",
    progress: 0,
    icon: "🌿",
    tasks: [
      { text: "选择适合的植物", points: 20 },
      { text: "准备种植工具", points: 20 },
      { text: "日常浇水养护", points: 30 },
      { text: "记录生长过程", points: 30 }
    ],
    tips: "选择适合室内种植的植物，如绿萝、多肉等"
  },
  {
    id: 7,
    title: "环保达人",
    description: "参与一次社区环保活动",
    points: 70,
    duration: "1天",
    category: "社区参与",
    difficulty: "简单",
    progress: 0,
    icon: "👥",
    tasks: [
      { text: "寻找环保活动", points: 10 },
      { text: "报名参与活动", points: 15 },
      { text: "完成志愿服务", points: 25 },
      { text: "分享活动经验", points: 20 }
    ],
    tips: "关注本地环保组织的公众号，及时了解活动信息"
  },
  {
    id: 8,
    title: "二手物品达人",
    description: "一个月内完成3次物品交换或二手物品交易",
    points: 110,
    duration: "30天",
    category: "资源循环",
    difficulty: "中等",
    progress: 0,
    icon: "🔄",
    tasks: [
      { text: "整理闲置物品", points: 20 },
      { text: "发布交换信息", points: 30 },
      { text: "完成物品交换", points: 30 },
      { text: "分享交换经验", points: 30 }
    ],
    tips: "可以使用闲置物品交换平台，既环保又能获得所需物品"
  }
];

function ChallengeCard({ challenge, onParticipate, onView, isParticipating, progress, loading }) {
  return (
    <Card sx={{
      height: '100%',
      display: 'flex',
      flexDirection: 'column',
      transition: 'transform 0.2s',
      '&:hover': {
        transform: 'translateY(-4px)',
        boxShadow: 4
      }
    }}>
      <CardContent sx={{ flexGrow: 1 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
          <Avatar sx={{ mr: 2, bgcolor: 'primary.main' }}>
            {challenge.icon}
          </Avatar>
          <Typography variant="h6" gutterBottom>
            {challenge.title}
          </Typography>
        </Box>
        <Typography variant="body2" color="text.secondary" paragraph>
          {challenge.description}
        </Typography>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
          <TimerIcon sx={{ mr: 1, fontSize: 20 }} />
          <Typography variant="body2">
            时长: {challenge.duration}
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
          <StarsIcon sx={{ mr: 1, fontSize: 20, color: 'gold' }} />
          <Typography variant="body2">
            积分: {challenge.points}
          </Typography>
        </Box>
        <Box sx={{ mt: 2 }}>
          <LinearProgress 
            variant="determinate" 
            value={progress}
            sx={{
              height: 8,
              borderRadius: 4,
              backgroundColor: 'rgba(0,0,0,0.1)',
              '& .MuiLinearProgress-bar': {
                borderRadius: 4
              }
            }}
          />
          <Typography variant="body2" color="text.secondary" align="right" sx={{ mt: 0.5 }}>
            {progress}%
          </Typography>
        </Box>
      </CardContent>
      <CardActions>
        <Button 
          size="small" 
          color="primary" 
          variant={isParticipating ? "outlined" : "contained"}
          onClick={() => isParticipating ? onView(challenge) : onParticipate(challenge)}
          disabled={loading}
          sx={{ flex: 1, mr: 1 }}
        >
          {loading ? 'Loading...' : isParticipating ? "查看进度" : "立即参与"}
        </Button>
      </CardActions>
    </Card>
  );
}

function ChallengeDetails({ challenge, open, onClose, isParticipating }) {
  if (!challenge) return null;

  return (
    <Dialog 
      open={open} 
      onClose={onClose}
      maxWidth="sm"
      fullWidth
    >
      <DialogTitle sx={{ m: 0, p: 2, display: 'flex', alignItems: 'center' }}>
        <Avatar sx={{ mr: 2, bgcolor: 'primary.main' }}>{challenge.icon}</Avatar>
        <Typography variant="h6">{challenge.title}</Typography>
        <IconButton
          onClick={onClose}
          sx={{ ml: 'auto' }}
        >
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      <DialogContent dividers>
        <Typography gutterBottom>{challenge.description}</Typography>
        <Typography variant="h6" gutterBottom sx={{ mt: 2 }}>
          任务清单：
        </Typography>
        <Box sx={{ mb: 2 }}>
          {challenge.tasks.map((task, index) => (
            <Chip
              key={index}
              label={task.text || task}
              sx={{ m: 0.5 }}
              color="primary"
              variant="outlined"
            />
          ))}
        </Box>
        <Box sx={{ mb: 2 }}>
          {challenge.tasks.map((task, index) => (
            <Box key={index} sx={{ mb: 1 }}>
              <Typography variant="body2">
                {task.text || task}
                {task.points && (
                  <Chip
                    label={`${task.points} 积分`}
                    size="small"
                    color="primary"
                    sx={{ ml: 1 }}
                  />
                )}
              </Typography>
            </Box>
          ))}
        </Box>
        <Typography variant="h6" gutterBottom>
          小贴士：
        </Typography>
        <Typography color="text.secondary">
          {challenge.tips}
        </Typography>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>关闭</Button>
        {!isParticipating && (
          <Button variant="contained" color="primary" onClick={onClose}>
            开始挑战
          </Button>
        )}
      </DialogActions>
    </Dialog>
  );
}

function Challenges() {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [challenges, setChallenges] = useState([]);
  const [selectedChallenge, setSelectedChallenge] = useState(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [participatingChallenges, setParticipatingChallenges] = useState(new Set());
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');

  // 分类标签数据
  const categories = [
    { value: 'all', label: '全部', icon: '🌍' },
    { value: 'lifestyle', label: '生活方式', icon: '🏠' },
    { value: 'transport', label: '绿色出行', icon: '🚲' },
    { value: 'energy', label: '节能减排', icon: '⚡' },
    { value: 'waste', label: '垃圾分类', icon: '♻️' },
    { value: 'food', label: '食物环保', icon: '🥗' },
    { value: 'garden', label: '绿色种植', icon: '🌿' },
    { value: 'community', label: '社区行动', icon: '👥' }
  ];

  // 过滤挑战
  const filteredChallenges = challenges.filter(challenge => 
    selectedCategory === 'all' || challenge.category === selectedCategory
  );

  // 获取挑战列表
  useEffect(() => {
    const fetchChallenges = async () => {
      try {
        setLoading(true);
        const response = await axios.get('/api/challenges');
        setChallenges(response.data);
      } catch (error) {
        console.error('获取挑战列表失败:', error);
        setError('获取挑战列表失败，请稍后重试');
      } finally {
        setLoading(false);
      }
    };
    fetchChallenges();
  }, []);

  const handleParticipate = async (challenge) => {
    try {
      // 检查用户是否登录
      if (!user) {
        // 可以显示登录对话框或跳转到登录页面
        setError('请先登录后再参与挑战');
        return;
      }

      setLoading(true);
      
      if (!challenge._id) {
        throw new Error('无效的挑战ID');
      }

      const response = await axios.post(`/api/challenges/${challenge._id}/participate`);
      
      if (response.data.success) {
        setParticipatingChallenges(prev => new Set([...prev, challenge._id]));
        setSelectedChallenge(challenge);
        setDialogOpen(true);
      }
    } catch (error) {
      console.error('参与挑战失败:', error);
      const errorMessage = error.response?.data?.message || '参与挑战失败，请稍后重试';
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleShowDetails = (challenge) => {
    setSelectedChallenge(challenge);
    setDialogOpen(true);
  };

  return (
    <Container maxWidth="lg">
      <Box sx={{ my: 4 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 4 }}>
          <TrophyIcon sx={{ fontSize: 40, mr: 2, color: 'primary.main' }} />
          <Typography variant="h4" component="h1">
            环保挑战
          </Typography>
        </Box>

        {/* 分类标签 */}
        <Box sx={{ mb: 4, display: 'flex', flexWrap: 'wrap', gap: 1 }}>
          {categories.map((category) => (
            <Chip
              key={category.value}
              label={
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <span style={{ marginRight: '4px' }}>{category.icon}</span>
                  {category.label}
                </Box>
              }
              onClick={() => setSelectedCategory(category.value)}
              color={selectedCategory === category.value ? "primary" : "default"}
              variant={selectedCategory === category.value ? "filled" : "outlined"}
              sx={{ 
                px: 1,
                '&:hover': {
                  bgcolor: theme => 
                    selectedCategory === category.value 
                      ? 'primary.main' 
                      : 'action.hover'
                }
              }}
            />
          ))}
        </Box>

        {/* 模块标题 */}
        {selectedCategory !== 'all' && (
          <Typography variant="h5" sx={{ mb: 3, color: 'primary.main' }}>
            {categories.find(c => c.value === selectedCategory)?.label}
          </Typography>
        )}

        {/* 错误提示 */}
        {error && (
          <Alert 
            severity="error" 
            onClose={() => setError('')}
            sx={{ mb: 3 }}
          >
            {error}
          </Alert>
        )}

        {/* 挑战列表 */}
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}>
            <CircularProgress />
          </Box>
        ) : (
          <>
            {selectedCategory === 'all' ? (
              // 按分类分组显示
              categories.slice(1).map(category => (
                <Box key={category.value} sx={{ mb: 8 }}>
                  <Typography 
                    variant="h5" 
                    sx={{ 
                      mb: 4, 
                      display: 'flex', 
                      alignItems: 'center',
                      position: 'relative',
                      '&::after': {
                        content: '""',
                        position: 'absolute',
                        bottom: -8,
                        left: 0,
                        width: '60px',
                        height: '3px',
                        bgcolor: 'primary.main'
                      }
                    }}
                  >
                    <span style={{ 
                      marginRight: '12px',
                      fontSize: '1.5em' 
                    }}>
                      {category.icon}
                    </span>
                    {category.label}
                  </Typography>
                  <Grid container spacing={3}>
                    {challenges
                      .filter(challenge => challenge.category === category.value)
                      .map((challenge) => (
                        <Grid item xs={12} md={4} key={challenge._id}>
                          <ChallengeCard
                            challenge={challenge}
                            onParticipate={handleParticipate}
                            onView={handleShowDetails}
                            isParticipating={participatingChallenges.has(challenge._id)}
                            progress={0}
                            loading={loading}
                          />
                        </Grid>
                      ))}
                  </Grid>
                </Box>
              ))
            ) : (
              // 显示选中分类的挑战
              <Grid container spacing={3}>
                {filteredChallenges.map((challenge) => (
                  <Grid item xs={12} md={4} key={challenge._id}>
                    <ChallengeCard
                      challenge={challenge}
                      onParticipate={handleParticipate}
                      onView={handleShowDetails}
                      isParticipating={participatingChallenges.has(challenge._id)}
                      progress={0}
                      loading={loading}
                    />
                  </Grid>
                ))}
              </Grid>
            )}
          </>
        )}
      </Box>

      {/* 登录对话框 */}
      <LoginDialog 
        open={!user && !!error} 
        onClose={() => setError('')}
        onSuccess={() => {
          setError('');
          // 如果有待参与的挑战，可以在这里重新触发参与操作
        }}
      />

      <ChallengeDetails
        challenge={selectedChallenge}
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        isParticipating={selectedChallenge && participatingChallenges.has(selectedChallenge._id)}
      />
    </Container>
  );
}

export default Challenges; 